import {useState} from "react"

import SquareNode from "./Square.jsx"
import HistoryLi from "./historyLis.jsx"

function getNextLetter(newArr){
  let contentCount = newArr.filter(item=>item!=null).length
  let newWord = contentCount%2===0?"X":"O"
  return newWord
}

function calculateWinner(newArr){
   const winnerConditions = [
    [0,1,2],
    [3,4,5],
    [6,7,8],
    [0,3,6],
    [1,4,7],
    [2,5,8],
    [0,4,8],
    [2,4,6]
   ]
   for(let i =0;i<winnerConditions.length;i++){
    let [a,b,c] = winnerConditions[i]
    let res = null
    if(newArr[a] && newArr[a]===newArr[b] && newArr[a]===newArr[c]){
        res = newArr[a]
        return res
    }
    return res
   }
  return newArr[0]
}

function getStatusWord(nextLetter,winner){
  if(winner){
      return `the winner is ${winner}`
  }else if(nextLetter){
      return `the next move is ${nextLetter}`
  }
  // return `the next move is ${nextLetter}`
}


function Board(){
  //渲染历史记录
  const [historyArr,sethistoryArr] = useState([])
  const handleLi = (index)=>{
    const item = historyArr[index].arr
    setNumArr(item)
    const oldArr = historyArr.slice(0,index+1)
    sethistoryArr(oldArr)
  }


   const [numArr,setNumArr] = useState(Array(9).fill(null))
   let nextLetter = getNextLetter(numArr)
   let winner = calculateWinner(numArr)
   let status = getStatusWord(nextLetter,winner)
   const handleClickInput = (index)=>{
      const newArr = numArr.slice()
      //重复位置无法下棋
      if(newArr[index])return
      //有胜利者无法继续下棋
      if(winner)return
      newArr[index] = nextLetter
      setNumArr(newArr)
      const arritem = {
        x:newArr.filter(item=>item==='X').length,
        o:newArr.filter(item=>item==='O').length,
        arr:newArr
      }
      const oldArr = historyArr.slice()
      oldArr.push(arritem)
      sethistoryArr(oldArr)
    }
    return(
        <>
        <h1>{status}</h1>
        <div className="board-row">
            <SquareNode index={0} value={numArr[0]} handleClick={handleClickInput} />
            <SquareNode index={1} value={numArr[1]} handleClick={handleClickInput} />
            <SquareNode index={2} value={numArr[2]} handleClick={handleClickInput} />
        </div>
          <div className="board-row">
           <SquareNode index={3} value={numArr[3]} handleClick={handleClickInput} />
            <SquareNode index={4} value={numArr[4]} handleClick={handleClickInput} />
            <SquareNode index={5} value={numArr[5]} handleClick={handleClickInput} />
        </div>
          <div className="board-row">
          <SquareNode index={6} value={numArr[6]} handleClick={handleClickInput} />
            <SquareNode index={7} value={numArr[7]} handleClick={handleClickInput} />
            <SquareNode index={8} value={numArr[8]} handleClick={handleClickInput} />
        </div>
        <ul>
          {historyArr.map((item,index)=><HistoryLi item={item} handleLi={handleLi} index={index}/>)}
        </ul>
        </>
    )
}

export default Board